package com.k8sops.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.k8sops.backend.mapper.DOSReleaseYamlMapper;
import com.k8sops.backend.model.entity.DOSReleaseYaml;
import com.k8sops.backend.service.DOSReleaseYamlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * DOSReleaseYaml服务实现类
 */
@Service
@Slf4j
public class DOSReleaseYamlServiceImpl extends ServiceImpl<DOSReleaseYamlMapper, DOSReleaseYaml> implements DOSReleaseYamlService {

    @Override
    public Integer saveYamlContent(Integer releaseId, Integer version, String yamlContent) {
        try {
            DOSReleaseYaml yaml = new DOSReleaseYaml();
            yaml.setReleaseId(releaseId);
            yaml.setVersion(version);
            yaml.setYamlContent(yamlContent);
            yaml.setCreateTime(LocalDateTime.now());

            // 保存YAML内容记录
            boolean saved = this.save(yaml);
            if (saved) {
                log.info("成功保存YAML内容, releaseId: {}, version: {}", releaseId, version);
                return yaml.getId().intValue();
            } else {
                log.error("保存YAML内容失败, releaseId: {}, version: {}", releaseId, version);
                return null;
            }
        } catch (Exception e) {
            log.error("保存YAML内容时出错", e);
            return null;
        }
    }

    @Override
    public String getYamlContentById(Integer id) {
        try {
            DOSReleaseYaml yaml = this.getById(id);
            if (yaml != null) {
                return yaml.getYamlContent();
            } else {
                log.warn("未找到对应的YAML内容记录, id: {}", id);
                return null;
            }
        } catch (Exception e) {
            log.error("获取YAML内容时出错", e);
            return null;
        }
    }

    @Override
    public DOSReleaseYaml getLatestYamlByReleaseId(Integer releaseId) {
        try {
            // 根据releaseId查询，并按版本号降序排序，取第一条记录
            LambdaQueryWrapper<DOSReleaseYaml> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DOSReleaseYaml::getReleaseId, releaseId)
                    .orderByDesc(DOSReleaseYaml::getVersion)
                    .orderByDesc(DOSReleaseYaml::getCreateTime)
                    .last("LIMIT 1");

            DOSReleaseYaml yaml = this.getOne(queryWrapper);
            if (yaml != null) {
                log.info("成功获取最新的YAML内容, releaseId: {}, version: {}", releaseId, yaml.getVersion());
                return yaml;
            } else {
                log.warn("未找到对应的YAML内容记录, releaseId: {}", releaseId);
                return null;
            }
        } catch (Exception e) {
            log.error("获取最新YAML内容时出错", e);
            return null;
        }
    }
}
